﻿namespace Huayou.Utils
{
    using System;
    using System.Data;

    public class CodeUtils
    {
        public static string NextCode(string parentCode, int childLen, DataTable dt, string colStr)
        {
            string str = null;
            string format = null;
            int num;
            int length;
            for (num = 0; num < childLen; num++)
            {
                format = format + "0";
            }
            format = "{0:" + format + "}";
            if (parentCode == null)
            {
                length = 0;
            }
            else if (parentCode == "0")
            {
                length = 0;
            }
            else
            {
                length = parentCode.Length;
            }
            DataView defaultView = dt.DefaultView;
            if (length == 0)
            {
                defaultView.RowFilter = string.Concat(new object[] { "len(", colStr, ")=", childLen });
            }
            else
            {
                defaultView.RowFilter = string.Concat(new object[] { "substring(", colStr, ",1,", length, ")='", parentCode, "' and len(", colStr, ")=", Convert.ToString((int) (length + childLen)) });
            }
            defaultView.Sort = colStr;
            if (defaultView != null)
            {
                if (defaultView.Count == 0)
                {
                    str = string.Format(format, 1);
                }
                else
                {
                    int count = defaultView.Count;
                    if (length != 0)
                    {
                        for (num = 0; num < count; num++)
                        {
                            string str3 = defaultView[num].Row[colStr].ToString().Substring(length, childLen);
                            if ((num + 1) < Convert.ToInt32(str3))
                            {
                                str = string.Format(format, num + 1);
                                count = num + 1;
                            }
                        }
                        if (str == null)
                        {
                            str = string.Format(format, defaultView.Count + 1);
                        }
                    }
                    else
                    {
                        str = string.Format(format, count + 1);
                    }
                }
            }
            else
            {
                str = string.Format(format, 1);
            }
            if (!((parentCode == null) || parentCode.Equals("0")))
            {
                str = parentCode + str;
            }
            return str;
        }
    }
}

